import sys
import traceback
from tkinter import messagebox

files = []
for i in range(0, 1531):
    filename = '/media/jz/My Passport/gate_pass_info/gate_pass_info_{}'.format(i)
    f = open(filename, 'w', encoding='utf8')
    files.append(f)


secret_index_cache = {}
with open('../index_result.txt', 'r', encoding='utf8') as f:
    for line in f:
        line = line.replace('"', '').replace('\n', '').replace("'", "")

        line_split = line.split('=')
        secret_card = line_split[0]
        table_index = line_split[1]
        if secret_card in secret_index_cache:
            print('same secret_card in file, secret is {}'.format(secret_card))
            sys.exit(-1)
        secret_index_cache[secret_card] = table_index
print('secret_index_cache count is {}'.format(len(secret_index_cache)))


for i in range(0, 1531):
    filename = '/home/jz/gate_pass_info_device/gate_pass_info_device_{}'.format(i)
    with open(filename, 'r', encoding='utf8') as f:
        try:
            line_number = 0
            for line in f:
                line_number += 1
                if line == '"\n':
                    continue

                line = line.replace('"', '').replace('\n', '').replace("'", "")
                line_split = line.split(',')
                if len(line_split) < 8 or line_split[7] == '':
                    continue

                secret_card = line_split[-1]
                index = int(secret_index_cache[secret_card])
                insert_file = files[index]
                insert_file.write(line + '\n')
        except Exception as e:
            # messagebox.showinfo("提示", "发生错误")
            print("filename={}, line={}".format(filename, line))
            traceback.print_exc()
            messagebox.showinfo("提示", "发生错误")
            sys.exit(-1)
        print('finish {}'.format(filename))


for file in files:
    file.close()

print('write all data finish')